<?php

//服务器端代码
// 创建websocket服务器对象，监听0.0.0.0:9501端口
$ws = new swoole_websocket_server("0.0.0.0", 9501); //监听9501端口


// on 函数 open message close

//监听WebSocket连接打开事件，客户端发来消息时触发
$ws->on('open', function ($ws, $request) {
    //var_dump($request->fd, $request->get, $request->server);
    echo "新用户 $request->fd 加入\n";
    $GLOBALS['fd'][$request->fd]['id'] = $request->fd; //设置用户ID
    $GLOBALS['fd'][$request->fd]['name'] = '匿名用户';  //设置用户名
    $GLOBALS['fd'][$request->fd]['status'] = 0;
});


//监听WebSocket消息事件
$ws->on('message', function ($ws, $request) {
    //var_dump($frame->fd, $frame->data, $frame->opcode, $frame->finish);
    $GLOBALS['fd'][$request->fd]['status'] = 1; //设置用户在线状态
    $msg = $GLOBALS['fd'][$request->fd]['name'] . ' ：' . $request->data ."\n";

    if(strstr($request->data, '#name#')){ //用户设置昵称
        $GLOBALS['fd'][$request->fd]['name'] = str_replace("#name#", '', $request->data);
    }else{ //进行用户信息发送
        // 发生每一个客户端
        foreach($GLOBALS['fd'] as $k => $v){
            if($request->fd != $k && $v['status'] == 1){ //发送消息给其他在线用户
                $ws->push($k, $msg);
            }
        }
    }
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    $GLOBALS['fd'][$fd]['status'] = 0; //设置用户离线状态
    echo "客户端- $fd 断开连接\n";
    unset($GLOBALS['fd'][$fd]); //删除用户信息
});


$ws->start(); //启动服务器